
#include <boost/lexical_cast.hpp>
#include "Session.h"

using namespace boost;
using namespace boost::asio;

namespace Engine {

CSession::CSession() : mValidTime(0), mId(0)
{
}

CSession::CSession(int id) : mValidTime(0), mId(id)
{
}

CSession::~CSession()
{
}

void CSession::HandlePackage(udp::endpoint& ep, boost::shared_ptr<CPackage> p)
{
	int dev_id = boost::lexical_cast<int>(p->GetPropertie(string(PACKAGE_PROP_DEVICE)));
	DeviceRef dev = GetDevice(dev_id, p->IsRequest());
	if(!dev) {
		return;
	}

	dev->SetEndpoint(ep);
	if(p->IsRequest()) {
		dev->HandleRequest(boost::dynamic_pointer_cast<CRequest, CPackage>(p));
	}
	else {
		dev->HandleResponse(boost::dynamic_pointer_cast<CResponse, CPackage>(p));
	}
}

bool CSession::AuthRequest(boost::shared_ptr<CRequest> r)
{
	int dev_id = r->GetPropertieInt(string(PACKAGE_PROP_DEVICE));
	DeviceRef dev = GetDevice(dev_id);
	if(!dev) {
		DebugStream << "CSession::AuthRequest - device not found : " << dev_id << '\n';
		return false;
	}

	string& token = r->GetPropertie(string(PACKAGE_PROP_TOKEN));
	if(token.length() == 0) {
		DebugStream << "CSession::AuthRequest - token not exiest : " << dev_id << '\n';
		return false;
	}

	if(token != dev->GetToken()) {
		DebugStream << "CSession::AuthRequest - token is  " << token << ", expect " << dev->GetToken() << '\n';
		return false;
	}

	return true;

}

void CSession::GetDesc(CPackage::JsonWriter& writer)
{
	boost::mutex::scoped_lock lock(mDataMutex);

	writer.StartObject();
	writer.String("id").Int(mId);
	writer.String("user").String(mUser->mName.c_str());
	writer.String("device-count").Int(mDevices.size());
	writer.String("device-list");
	string devs;
	for(list<DeviceRef>::iterator i = mDevices.begin(); i != mDevices.end(); i++) {
		devs.append(boost::lexical_cast<string>((*i)->GetId()));
		devs.push_back(',');
	}
	writer.String(devs.c_str());
	writer.EndObject();
}

}
